import { defineStore } from 'pinia'
import request from '@/utils/request'
import { ApiRes } from '@/types/data'
import { CartItem } from '@/types/cart'
import useStore from '..'
import { Sku } from '@/types/goods'

const useCartStore = defineStore('cart', {
	persist: {
		// 开启数据持久化,并且指定key值
		key: 'rabbit-cart',
	},
	state: () => {
		return {
			list: [] as CartItem[], // 购物车列表
		}
	},
	actions: {
		async addCart(data: CartItem) {
			if (this.isLogin) {
				await request.post('/member/cart', {
					skuId: data.skuId,
					count: data.count,
				})
				// 刷新 获取购物车列表
				this.getCartList()
			} else {
				// 本地逻辑
				// 1、判断购物车是否已经存在skuId商品
				const goods = this.effectiveList.find((item) => item.skuId === data.skuId)
				// 已经存在
				if (goods) {
					goods.count += data.count
				} else {
					// 不存在
					this.list.unshift(data)
				}
			}
		},
		// 获取购物车列表
		async getCartList() {
			if (this.isLogin) {
				const res = await request.get<ApiRes<CartItem[]>>('/member/cart')
				this.list = res.data.result
			} else {
				// 本地数据可能会过期, 例如商品价格
				this.list.forEach(async (item) => {
					const { skuId } = item
					const res = await request.get<ApiRes<CartItem>>(`/goods/stock/${skuId}`)
					const { stock, nowPrice, isEffective } = res.data.result
					item.stock = stock
					item.nowPrice = nowPrice
					item.isEffective = isEffective
				})
			}
		},
		// 删除购物车列表
		async deleteCart(skuIds: string[]) {
			if (this.isLogin) {
				await request.delete('member/cart', {
					// delete要求是body传参
					data: { ids: skuIds },
				})
				// 刷新 获取购物车列表
				this.getCartList()
			} else {
				// 从本地删除
				this.list = this.list.filter((item) => !skuIds.includes(item.skuId))
			}
		},
		async updateCart(skuId: string, data: { selected?: boolean; count?: number }) {
			if (this.isLogin) {
				await request.put(`/member/cart/${skuId}`, data)
				// 刷新 获取购物车列表
				this.getCartList()
			} else {
				const cartItem = this.list.find((item) => item.skuId === skuId)
				if (cartItem) {
					if (data.count !== undefined) cartItem.count = data.count
					if (data.selected !== undefined) cartItem.selected = data.selected
				}
			}
		},
		async updateCartAllSelected(isAllSelected: boolean) {
			if (this.isLogin) {
				await request.put('/member/cart/selected', {
					selected: isAllSelected,
				})
				// 刷新 获取购物车列表
				this.getCartList()
			} else {
				this.effectiveList.forEach((item) => (item.selected = isAllSelected))
			}
		},
		async updateCartSku(oldSkuId: string, sku: Sku) {
			if (this.isLogin) {
				const oldSku = this.effectiveList.find((item) => item.skuId === oldSkuId)
				await request.delete('member/cart', {
					// delete要求是body传参
					data: { ids: [oldSkuId] },
				})
				await this.addCart({
					skuId: sku.id,
					count: oldSku?.count!,
				} as CartItem)
			} else {
				// 删除
				const oldSku = this.effectiveList.find((item) => item.skuId === oldSkuId)!
				this.deleteCart([oldSkuId])
				// 添加
				this.addCart({
					...oldSku,
					skuId: sku.id,
					nowPrice: sku.price,
					stock: sku.inventory,
					attrsText: sku.specs.map((item) => item.name + ':' + item.valueName).join(' '),
				})
			}
		},
		clearCart() {
			this.list = []
		},
		// 合并购物车
		async mergeLocalCart() {
			const data = this.list.map(({ skuId, selected, count }) => ({
				skuId,
				selected,
				count,
			}))
			await request.post('/member/cart/merge', data)
			//合并成功 刷新购物车列表
			this.getCartList()
		},
	},
	getters: {
		isLogin(): boolean {
			const { user } = useStore()
			return !!user.profile.token
		},
		// 有效的商品列表
		effectiveList(): CartItem[] {
			return this.list.filter((item) => item.stock > 0 && item.isEffective)
		},
		// 所有有效的商品的数量
		effectiveListCounts(): number {
			return this.effectiveList.reduce((sum, item) => {
				return sum + item.count
			}, 0)
		},
		// 所有有效商品的总价钱
		effectiveListPrice(): number {
			return +this.effectiveList
				.reduce((sum, item) => {
					return sum + item.count * Number(item.nowPrice)
				}, 0)
				.toFixed(2)
		},
		isAllSelected(): boolean {
			return this.effectiveList.every((item) => item.selected)
		},
		selectedList(): CartItem[] {
			return this.effectiveList.filter((item) => item.selected)
		},
		selectedListCounts(): number {
			return this.selectedList.reduce((sum, item) => {
				return sum + item.count
			}, 0)
		},
		selectedListPrice(): number {
			return +this.selectedList
				.reduce((sum, item) => {
					return sum + item.count * Number(item.nowPrice)
				}, 0)
				.toFixed(2)
		},
	},
})

export default useCartStore
